import hashlib
import json
import time

import jwt
from django.shortcuts import render
from django.http import JsonResponse
from app01 import models
from django.conf import settings


# Create your views here.
def tokens(request):
    if request.method != 'POST':
        return JsonResponse({'code': 400, 'error': "请求方式错误!"})
    # 校验用户名密码
    json_str = request.body
    data = json.loads(json_str)
    username = data['username']
    password = data['password']
    # 效验用户名和密码
    try:
        user = models.AdminProfile.objects.get(username=username)
    except Exception as e:
        result = {'code': 500, 'error': "用户名或密码错误!"}
        return JsonResponse(result)
    p_m = hashlib.md5()
    p_m.update(password.encode())
    if p_m.hexdigest() != user.password:
        result = {'code': 500, 'error': "用户名或密码错误!"}
        return JsonResponse(result)
    # 记录会话状态
    token = make_token(username)
    result = {'code': 200, 'username': username, 'data': {'token': token, 'avatar': str(user.avatar)}}
    return JsonResponse(result)


def u_tokens(request):
    if request.method != 'POST':
        return JsonResponse({'code': 400, 'error': "请求方式错误!"})
    # 校验用户名密码
    json_str = request.body
    data = json.loads(json_str)
    username = data['username']
    password = data['password']

    # 效验用户名和密码
    try:
        user = models.UserProfile.objects.get(username=username)
    except Exception as e:
        result = {'code': 500, 'error': "用户名或密码错误!"}
        return JsonResponse(result)
    p_m = hashlib.md5()
    p_m.update(password.encode())

    if p_m.hexdigest() != user.password:
        result = {'code': 500, 'error': "用户名或密码错误!2"}
        return JsonResponse(result)
    # 记录会话状态
    token = make_token(username)
    result = {'code': 200, 'username': user.username, 'nickname':user.nickname,'data': {'token': token, 'avatar': str(user.avatar)}}
    return JsonResponse(result)


def make_token(username, expire=3600 * 24):
    key = settings.JWT_TOKEN_KEY
    now_t = time.time()
    payload_data = {'username': username, 'exp': now_t + expire}
    return jwt.encode(payload_data, key, algorithm='HS256')
